package com.magold.event;

import org.andengine.engine.handler.IUpdateHandler;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;

/**
 * force value: minForce -> maxForce -> minForce -> maxForce -> * * *
 * 
 * @author Eternity
 *
 */
public class ApplyForcePeriodicallyResult extends TargetResult<EventDrivable> implements IUpdateHandler {
	private final Vector2 mMinForce;
	private final Vector2 mMaxForce;
	private float mCycle;
	private float mElaspedTime;
	
	/**
	 * 
	 * @param pForce1
	 * @param pForce2
	 * @param pCycle time that pMinForce change to pMaxForce need.
	 * @param pTarget
	 */
	public ApplyForcePeriodicallyResult(Vector2 pForce1, Vector2 pForce2, float pCycle, EventDrivable pTarget) {
		super(pTarget);
		mMinForce = pForce1;
		mMaxForce = pForce2;
		mCycle = pCycle;
	}

	@Override
	public IUpdateHandler onConditionMatched(int pTimes) {
		return this;
	}

	@Override
	public IUpdateHandler onConditionMismatched() {
		return null;
	}

	@Override
	public TargetResult<EventDrivable> copy(EventDrivable pNewTarget) {
		return new ApplyForcePeriodicallyResult(mMinForce, mMaxForce, mCycle/2, pNewTarget);
	}

	@Override
	public void onUpdate(final float pSecondsElapsed) {
		Body body = mTarget.getBody();
		if (body == null) return;
		
		mElaspedTime = (mElaspedTime + pSecondsElapsed) % mCycle;
		
		int i = (int) (mElaspedTime / (mCycle / 4));
		
		Vector2 force = i==0 || i==3 ? mMinForce : mMaxForce;

		body.applyForce(force, body.getWorldCenter());
	}
	
	@Override
	public void reset() {
	}

}
